package com.heima.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.domain.dto.PageDto;
import com.heima.domain.po.Item;
import com.heima.domain.query.ItemPageQuery;
import com.heima.domain.vo.FiltersVo;
import com.heima.dto.ItemDTO;
import com.heima.service.SearchService;
import com.heima.srevice.IItemService;
import com.hmall.common.domain.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {

    private final IItemService itemService;

    private final SearchService searchService;

    @ApiOperation("搜索商品")
    @GetMapping
    public PageDTO<ItemDTO> search(ItemPageQuery query) {
        // 分页查询
        Page<Item> result = itemService.lambdaQuery()
                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
                .eq(Item::getStatus, 1)
                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
                .page(query.toMpPage("price", false));
        long pages = result.getPages();
        System.out.println("总页数："+pages);
        // 封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }

    @ApiOperation("数据批量导入")
    @GetMapping(value = "/init")
    public String initData() throws IOException {
        searchService.initData();
        return "SUCCESS";
    }

    @ApiOperation("es搜索商品")
    @GetMapping("/list")
    public PageDto<ItemDTO> esSearch(ItemPageQuery query) throws IOException {
        return searchService.esSearch(query);
    }

    @ApiOperation("过滤条件")
    @PostMapping("/filters")
    public Map<String,List<String>> filters(@RequestBody FiltersVo filtersVo) throws IOException {
        return searchService.filters(filtersVo);
    }
}
